package cn.edu.tju.cas.service.impl;

import cn.edu.tju.cas.dao.GroupDao;
import cn.edu.tju.cas.dao.GroupFormDao;
import cn.edu.tju.cas.dao.UserGroupApplyDao;
import cn.edu.tju.cas.dao.impl.GroupDaoImpl;
import cn.edu.tju.cas.entity.GroupEntity;
import cn.edu.tju.cas.entity.GroupFormEntity;
import cn.edu.tju.cas.entity.UserGroupApplyEntity;
import cn.edu.tju.cas.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.acl.Group;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by catold on 16/3/12.
 */
@Service("groupService")
public class GroupServiceImpl extends BaseServcieImpl<GroupEntity, GroupDao> implements GroupService {
    @Autowired
    private GroupDao groupDao;

    @Autowired
    private GroupFormDao groupFormDao;

    @Autowired
    private UserGroupApplyDao userGroupApplyDao;

    @Resource(name = "groupDao")
    public void setDao(GroupDao groupDao) {
        super.setDao(groupDao);
    }

    @Override
    public void addGroupAndForm(GroupEntity groupEntity) {
        if(groupEntity != null) {
//            int groupId = groupDao.save(groupEntity);
//            for (GroupFormEntity groupFormEntity : groupEntity.getGroupForms()) {
//                groupFormEntity.setGroupId(groupId);
//                groupFormDao.save(groupFormEntity);
//            }
            groupDao.save(groupEntity);
        }
    }

    @Override
    public void deleteById(int groupId) {
        List<UserGroupApplyEntity> userGroupApplyEntities = userGroupApplyDao.getUserApplyByGroupId(groupId);
        if(userGroupApplyEntities != null){
            for(UserGroupApplyEntity userGroupApplyEntity:userGroupApplyEntities){
                userGroupApplyDao.deleteById(userGroupApplyEntity.getUserGroupApplyId());
            }
        }
//        GroupEntity groupEntity = this.findById(groupId);
//        Set<GroupFormEntity> groupFormEntitys = groupEntity.getGroupForms();
        super.deleteById(groupId);
//        if(groupFormEntitys != null){
//            Iterator<GroupFormEntity> iterator = groupFormEntitys.iterator();
//            while (iterator.hasNext()){
//                GroupFormEntity ele = iterator.next();
//                groupFormDao.deleteById(ele.getGroupId());
//
//            }
//        }

    }
}
